/**
 * 系统项目名称
 * com.csdn.leon.activity
 * BlogContentActivity.java
 * 
 * 2015-9-7-下午2:41:30
 *  2015XX公司-版权所有
 * 
 */
package com.csdn.leon.activity;

import java.io.File;
import java.util.Iterator;

import org.apache.http.Header;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.csdn.leon.base.BaseActivity;
import com.csdn.leon.db.DBUtil;
import com.csdn.leon.model.BlogModel;
import com.csdn.leon.net.CSDNapi;
import com.csdn.leon.util.Constants;
import com.csdn.leon.util.JsoupUtil;
import com.csdn.leon.util.ToastUtil;
import com.csdn.leon.view.popup.CustomShareBoard;
import com.loopj.android.http.TextHttpResponseHandler;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.laiwang.media.LWDynamicShareContent;
import com.umeng.socialize.laiwang.media.LWShareContent;
import com.umeng.socialize.media.GooglePlusShareContent;
import com.umeng.socialize.media.MailShareContent;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.QZoneShareContent;
import com.umeng.socialize.media.RenrenShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.SmsShareContent;
import com.umeng.socialize.media.TencentWbShareContent;
import com.umeng.socialize.media.TwitterShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMVideo;
import com.umeng.socialize.media.UMusic;
import com.umeng.socialize.sso.EmailHandler;
import com.umeng.socialize.sso.QZoneSsoHandler;
import com.umeng.socialize.sso.RenrenSsoHandler;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.SmsHandler;
import com.umeng.socialize.sso.TencentWBSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;
import com.umeng.socialize.weixin.media.CircleShareContent;
import com.umeng.socialize.weixin.media.WeiXinShareContent;
import com.csdn.leon.base.R;

/**
 * 项目名称：舒睡宝 版本号：V1.00 创建者:刘海 功能描述： 2015-9-7
 */

public class BlogContentActivity extends BaseActivity implements
		OnClickListener, OnCheckedChangeListener {
	private final UMSocialService mController = UMServiceFactory
			.getUMSocialService(Constants.DESCRIPTOR);
	private SHARE_MEDIA mPlatform = SHARE_MEDIA.SINA;

	private WebView mWebView = null;
	private String url;

	private TextView leftTv;
	private ImageView leftImg;
	private TextView middleTv;
	private ImageView mCommemtBtn;
	private ImageView mShareBtn;
	private ImageView mMoreBtn;
	private ToggleButton mCollectBtn;
	private BlogModel blogModel;

	private Dialog shareDialog;

	// private ToolShareSDK mShareSDK;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.activity_content_layout);
		init();
		initWebView();
		// 配置需要分享的相关平台
		configPlatforms();
		// 设置分享的内容
		setShareContent();
	}

	private void init() {
		url = this.getIntent().getExtras().getString("blog_url");
		blogModel = (BlogModel) getIntent().getSerializableExtra("blogmodel");
		Log.e("ddddddddddddd", blogModel.toString());
		leftTv = (TextView) findViewById(R.id.title_left_text);
		leftTv.setVisibility(View.GONE);
		leftImg = (ImageView) findViewById(R.id.title_left_img);
		leftImg.setVisibility(View.VISIBLE);
		leftImg.setImageResource(R.drawable.actionbar_back_icon_normal);
		leftImg.setOnClickListener(this);
		middleTv = (TextView) findViewById(R.id.title_middle_text);
		middleTv.setText("博客详情");
		mCommemtBtn = (ImageView) findViewById(R.id.iv_comment);
		mShareBtn = (ImageView) findViewById(R.id.iv_share);
		mMoreBtn = (ImageView) findViewById(R.id.iv_more);
		mCollectBtn = (ToggleButton) findViewById(R.id.tb_collect);

		if (blogModel != null
				&& DBUtil.queryBlogModel(this, blogModel.getTitle())) {
			mCollectBtn.setChecked(true);
		}
		mCommemtBtn.setOnClickListener(this);
		mShareBtn.setOnClickListener(this);
		mMoreBtn.setOnClickListener(this);
		mCollectBtn.setOnCheckedChangeListener(this);
	}

	private void initWebView() {
		mWebView = (WebView) findViewById(R.id.webview);
		mWebView.setWebViewClient(new MyWebViewClient());
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.getSettings().setDefaultTextEncodingName("utf-8");
		mWebView.getSettings().setAppCacheEnabled(true);
		mWebView.getSettings().setDatabaseEnabled(true);
		// 设置可以支持缩放
		mWebView.getSettings().setSupportZoom(true);
		// 设置出现缩放工具
		mWebView.getSettings().setBuiltInZoomControls(false);
		// 扩大比例的缩放
		// mWebView.getSettings()
		// .setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		// mWebView.getSettings().setLoadWithOverviewMode(true);

		// LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
		// LOAD_DEFAULT: 根据cache-control决定是否从网络上取数据。
		// 总结：根据以上两种模式，建议缓存策略为，判断是否有网络，有的话，使用LOAD_DEFAULT，无网络时，使用LOAD_CACHE_ELSE_NETWORK。
		mWebView.getSettings()
				.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		requestData(url);
	}

	private void requestData(String url) {
		showWaitDialog();
		CSDNapi.getBlogList(url, handle);
	}

	TextHttpResponseHandler handle = new TextHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, String arg2,
				Throwable arg3) {
			hideWaitDialog();
			Toast.makeText(BlogContentActivity.this, "加载失败，请重新加载...", 2000)
					.show();
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, String s) {
			Log.w("dd", s);
			// executeParserTask(s);
			String content = JsoupUtil.getContentHtml(s);
			String html = adjustPicSize(content);
			loadHtml(html);
			hideWaitDialog();
		}
	};

	/**
	 * 适应页面
	 * 
	 * @param paramString
	 * @return
	 */
	private String adjustPicSize(String paramString) {
		if (TextUtils.isEmpty(paramString)) {
			return null;
		}
		Element localElement = Jsoup.parse(paramString)
				.getElementsByClass("details").get(0);
		Iterator<?> localIterator = localElement.getElementsByTag("img")
				.iterator();
		while (true) {
			if (!localIterator.hasNext())
				return "<script type=\"text/javascript\" src=\"file:///android_asset/shCore.js\"></script><script type=\"text/javascript\" src=\"file:///android_asset/shBrushCpp.js\"></script><script type=\"text/javascript\" src=\"file:///android_asset/shBrushXml.js\"></script><script type=\"text/javascript\" src=\"file:///android_asset/shBrushJScript.js\"></script><script type=\"text/javascript\" src=\"file:///android_asset/shBrushJava.js\"></script><link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/shThemeDefault.css\"><link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/shCore.css\"><script type=\"text/javascript\">SyntaxHighlighter.all();</script>"
						+ localElement.toString();
			((Element) localIterator.next()).attr("width", "100%");
		}
	}

	/**
	 * 加载页面
	 * 
	 * @param resultString
	 */
	private void loadHtml(String html) {
		if (!TextUtils.isEmpty(html)) {
			mWebView.loadDataWithBaseURL("http://blog.csdn.net", html,
					"text/html", "utf-8", null);
			// mReLoadImageView.setVisibility(View.GONE);
		} else {
			// mProgressBar.setVisibility(View.GONE);
			// mReLoadImageView.setVisibility(View.VISIBLE);
			// ToastUtil.show(this, "网络已断开");
		}
	}

	/**
	 * 自定义
	 * 
	 * @author Administrator
	 * 
	 */
	class MyWebViewClient extends WebViewClient {

		MyWebViewClient() {

		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			super.onPageStarted(view, url, favicon);
		}

		public void onPageFinished(WebView paramWebView, String paramString) {
			mWebView.getSettings().setBlockNetworkImage(false);
			super.onPageFinished(paramWebView, paramString);
		}

		public void onReceivedError(WebView paramWebView, int paramInt,
				String paramString1, String paramString2) {
			super.onReceivedError(paramWebView, paramInt, paramString1,
					paramString2);
		}

		public boolean shouldOverrideUrlLoading(WebView paramWebView,
				String paramString) {
			if ((paramString
					.matches("http://blog.csdn.net/(\\w+)/article/details/(\\d+)"))) {
				// 将当前浏览页面加入历史记录
				// mHistoryUrlList.add(mUrl);

				// 加载新的页面
				url = paramString;
				requestData(paramString);
				return false;
			}
			return true;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_left_img:
			finish();
			break;
		case R.id.iv_share:
			CustomShareBoard shareBoard = new CustomShareBoard(this);
			shareBoard.showAtLocation(this.getWindow().getDecorView(),
					Gravity.BOTTOM, 0, 0);
			break;
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			ToastUtil.show(this, "收藏成功");
			DBUtil.insertBlogModel(BlogContentActivity.this, blogModel);
		} else {
			ToastUtil.show(this, "取消收藏");
			DBUtil.deleteBlogModel(BlogContentActivity.this,
					blogModel.getTitle());
		}

	}

	/**
	 * 添加短信平台</br>
	 */
	private void addSMS() {
		// 添加短信
		SmsHandler smsHandler = new SmsHandler();
		smsHandler.addToSocialSDK();
	}

	/**
	 * 添加Email平台</br>
	 */
	private void addEmail() {
		// 添加email
		EmailHandler emailHandler = new EmailHandler();
		emailHandler.addToSocialSDK();
	}

	/**
	 * 配置分享平台参数</br>
	 */
	private void configPlatforms() {
		
		// 添加新浪SSO授权
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		// 添加腾讯微博SSO授权
		mController.getConfig().setSsoHandler(new TencentWBSsoHandler());
		// 添加人人网SSO授权
		RenrenSsoHandler renrenSsoHandler = new RenrenSsoHandler(this,
				"201874", "28401c0964f04a72a14c812d6132fcef",
				"3bf66e42db1e4fa9829b955cc300b737");
		mController.getConfig().setSsoHandler(renrenSsoHandler);

		// 添加QQ、QZone平台
		addQQQZonePlatform();

		// 添加微信、微信朋友圈平台
		addWXPlatform();
		addSMS();
		addEmail();
	}

	/**
	 * @功能描述 : 添加微信平台分享
	 * @return
	 */
	private void addWXPlatform() {
		// 注意：在微信授权的时候，必须传递appSecret
		// wx967daebe835fbeac是你在微信开发平台注册应用的AppID, 这里需要替换成你注册的AppID
		String appId = "wx267252176f6891cd";
		String appSecret = "8bf86fc06eeff66d397327cc4cdd5bb8";
		// 添加微信平台
		UMWXHandler wxHandler = new UMWXHandler(this, appId, appSecret);
		wxHandler.addToSocialSDK();

		// 支持微信朋友圈
		UMWXHandler wxCircleHandler = new UMWXHandler(this, appId, appSecret);
		wxCircleHandler.setToCircle(true);
		wxCircleHandler.addToSocialSDK();
	}

	/**
	 * @功能描述 : 添加QQ平台支持 QQ分享的内容， 包含四种类型， 即单纯的文字、图片、音乐、视频. 参数说明 : title, summary,
	 *       image url中必须至少设置一个, targetUrl必须设置,网页地址必须以"http://"开头 . title :
	 *       要分享标题 summary : 要分享的文字概述 image url : 图片地址 [以上三个参数至少填写一个] targetUrl
	 *       : 用户点击该分享时跳转到的目标地址 [必填] ( 若不填写则默认设置为友盟主页 )
	 * @return
	 */
	private void addQQQZonePlatform() {
		String appId = "100424468";
		String appKey = "c7394704798a158208a74ab60104f0ba";
		// 添加QQ支持, 并且设置QQ分享内容的target url
		UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(this, appId, appKey);
		qqSsoHandler.setTargetUrl("http://blog.csdn.net/index.html");
		qqSsoHandler.addToSocialSDK();

		// 添加QZone平台
		QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this, appId,
				appKey);
		qZoneSsoHandler.addToSocialSDK();
	}

	/**
	 * 根据不同的平台设置不同的分享内容</br>
	 */
	private void setShareContent() {

		// 配置SSO
		mController.getConfig().setSsoHandler(new SinaSsoHandler());
		mController.getConfig().setSsoHandler(new TencentWBSsoHandler());

		QZoneSsoHandler qZoneSsoHandler = new QZoneSsoHandler(this,
				"1104777405", "LdLXOjYrfOZGVJU9");
		qZoneSsoHandler.addToSocialSDK();
		mController
				.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		mController.getConfig().setSsoHandler(qZoneSsoHandler);
		// APP ID：201874, API
		// * KEY：28401c0964f04a72a14c812d6132fcef, Secret
		// * Key：3bf66e42db1e4fa9829b955cc300b737.
		RenrenSsoHandler renrenSsoHandler = new RenrenSsoHandler(this,
				"201874", "28401c0964f04a72a14c812d6132fcef",
				"3bf66e42db1e4fa9829b955cc300b737");
		mController.getConfig().setSsoHandler(renrenSsoHandler);

		UMImage localImage = new UMImage(this, R.drawable.csdn);
		UMImage urlImage = new UMImage(this,
				"http://www.umeng.com/images/pic/social/integrated_3.png");
		// UMImage resImage = new UMImage(this, R.drawable.icon);

		// 视频分享
		UMVideo video = new UMVideo(
				"http://v.youku.com/v_show/id_XNTc0ODM4OTM2.html");
		// vedio.setThumb("http://www.umeng.com/images/pic/home/social/img-1.png");
		video.setTitle("友盟社会化组件视频");
		video.setThumb(urlImage);

		UMusic uMusic = new UMusic(
				"http://music.huoxing.com/upload/20130330/1364651263157_1085.mp3");
		uMusic.setAuthor("umeng");
		uMusic.setTitle("天籁之音");
		// uMusic.setThumb(urlImage);
		uMusic.setThumb("http://www.umeng.com/images/pic/social/chart_1.png");

		// UMEmoji emoji = new UMEmoji(this,
		// "http://www.pc6.com/uploadimages/2010214917283624.gif");
		// UMEmoji emoji = new UMEmoji(this,
		// "/storage/sdcard0/emoji.gif");

		WeiXinShareContent weixinContent = new WeiXinShareContent();
		weixinContent
				.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		weixinContent.setTitle("CSDN博客客户端");
		weixinContent.setTargetUrl(blogModel.getLink());
		weixinContent.setShareMedia(urlImage);
		mController.setShareMedia(weixinContent);

		// 设置朋友圈分享的内容
		CircleShareContent circleMedia = new CircleShareContent();
		circleMedia
				.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		circleMedia.setTitle("友盟社会化分享组件-朋友圈");
		circleMedia.setShareMedia(urlImage);
		// circleMedia.setShareMedia(uMusic);
		// circleMedia.setShareMedia(video);
		circleMedia.setTargetUrl("http://www.umeng.com/social");
		mController.setShareMedia(circleMedia);

		// 设置renren分享内容
		RenrenShareContent renrenShareContent = new RenrenShareContent();
		renrenShareContent.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		UMImage image = new UMImage(this, BitmapFactory.decodeResource(
				getResources(), R.drawable.csdn));
		image.setTitle("thumb title");
		image.setThumb("http://www.umeng.com/images/pic/social/integrated_3.png");
		renrenShareContent.setShareImage(image);
		renrenShareContent.setAppWebSite("http://www.umeng.com/social");
		mController.setShareMedia(renrenShareContent);

		UMImage qzoneImage = new UMImage(this,
				"http://www.umeng.com/images/pic/social/integrated_3.png");
		qzoneImage
				.setTargetUrl("http://www.umeng.com/images/pic/social/integrated_3.png");

		// 设置QQ空间分享内容
		QZoneShareContent qzone = new QZoneShareContent();
		qzone.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		qzone.setTargetUrl(blogModel.getLink());
		qzone.setTitle("CSDN博客客户端");
		qzone.setShareMedia(urlImage);
		// qzone.setShareMedia(uMusic);
		mController.setShareMedia(qzone);

		video.setThumb(new UMImage(this, BitmapFactory.decodeResource(
				getResources(), R.drawable.csdn)));

		QQShareContent qqShareContent = new QQShareContent();
		qqShareContent.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		qqShareContent.setTitle("CSDN博客客户端");
		qqShareContent.setShareMedia(image);
		qqShareContent.setTargetUrl(blogModel.getLink());
		mController.setShareMedia(qqShareContent);

		// 视频分享
		UMVideo umVideo = new UMVideo(
				"http://v.youku.com/v_show/id_XNTc0ODM4OTM2.html");
		umVideo.setThumb("http://www.umeng.com/images/pic/home/social/img-1.png");
		umVideo.setTitle("友盟社会化组件视频");

		TencentWbShareContent tencent = new TencentWbShareContent();
		tencent.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		// 设置tencent分享内容
		mController.setShareMedia(tencent);

		// 设置邮件分享内容， 如果需要分享图片则只支持本地图片
		MailShareContent mail = new MailShareContent(localImage);
		mail.setTitle("CSDN博客客户端");
		mail.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		// 设置tencent分享内容
		mController.setShareMedia(mail);

		// 设置短信分享内容
		SmsShareContent sms = new SmsShareContent();
		sms.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		// sms.setShareImage(urlImage);
		mController.setShareMedia(sms);

		SinaShareContent sinaContent = new SinaShareContent();
		sinaContent
				.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		sinaContent.setShareImage(new UMImage(this, R.drawable.csdn));
		mController.setShareMedia(sinaContent);

		TwitterShareContent twitterShareContent = new TwitterShareContent();
		twitterShareContent
				.setShareContent(blogModel.getTitle()+ " "+blogModel.getLink());
		twitterShareContent.setShareMedia(new UMImage(this, new File(
				"/storage/sdcard0/emoji.gif")));
		mController.setShareMedia(twitterShareContent);

		GooglePlusShareContent googlePlusShareContent = new GooglePlusShareContent();
		googlePlusShareContent
				.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能-G+。http://www.umeng.com/social");
		googlePlusShareContent.setShareMedia(localImage);
		mController.setShareMedia(googlePlusShareContent);

		// 来往分享内容
		LWShareContent lwShareContent = new LWShareContent();
		// lwShareContent.setShareImage(urlImage);
		// lwShareContent.setShareMedia(uMusic);
		lwShareContent.setShareMedia(umVideo);
		lwShareContent.setTitle("友盟社会化分享组件-来往");
		lwShareContent.setMessageFrom("友盟分享组件");
		lwShareContent
				.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能-来往。http://www.umeng.com/social");
		mController.setShareMedia(lwShareContent);

		// 来往动态分享内容
		LWDynamicShareContent lwDynamicShareContent = new LWDynamicShareContent();
		// lwDynamicShareContent.setShareImage(urlImage);
		// lwDynamicShareContent.setShareMedia(uMusic);
		lwDynamicShareContent.setShareMedia(umVideo);
		lwDynamicShareContent.setTitle("友盟社会化分享组件-来往动态");
		lwDynamicShareContent.setMessageFrom("来自友盟");
		lwDynamicShareContent
				.setShareContent("来自友盟社会化组件（SDK）让移动应用快速整合社交分享功能-来往动态。http://www.umeng.com/social");
		lwDynamicShareContent.setTargetUrl("http://www.umeng.com/social");
		mController.setShareMedia(lwDynamicShareContent);

	}

}
